package com.wanchuang.shengfubao.module.mine;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanchuang.shengfubao.MainActivity;
import com.wanchuang.shengfubao.R;
import com.wanchuang.shengfubao.base.BaseFragment;
import com.wanchuang.shengfubao.base.MainApplication;
import com.wanchuang.shengfubao.dialog.DialogUtils;
import com.wanchuang.shengfubao.help.GlideHelper;
import com.wanchuang.shengfubao.help.ImageHelper;
import com.wanchuang.shengfubao.help.PermissionHelper;
import com.wanchuang.shengfubao.help.ServiceBean;
import com.wanchuang.shengfubao.help.UserBean;
import com.wanchuang.shengfubao.help.UserHelper;
import com.wanchuang.shengfubao.module.login.LoginActivity;
import com.wanchuang.shengfubao.net.Apis;
import com.wanchuang.shengfubao.net.NetworkManager;
import com.wanchuang.shengfubao.net.WebApis;
import com.wanchuang.shengfubao.net.interfaces.OnRequestCallBack;
import com.wanchuang.shengfubao.net.interfaces.OnUpLoadCallBack;
import com.wanchuang.shengfubao.proto.Index;
import com.wanchuang.shengfubao.proto.MemberOuterClass;
import com.wanchuang.shengfubao.utils.ValidateUtils;
import com.wanchuang.shengfubao.view.MineItemLayout;
import com.example.havi.helper.ChatHelper;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.ui.ChatActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import com.wanchuang.shengfubao.web.ui.WebViewActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class MineFragment extends BaseFragment {
    Unbinder unbinder;
    @BindView(R.id.mine_mil_one)
    MineItemLayout mineMilOne;
    @BindView(R.id.mine_mil_two)
    MineItemLayout mineMilTwo;
    @BindView(R.id.login_out)
    Button loginOut;
    @BindView(R.id.tv_usename)
    TextView tv_usename;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.iv_head)
    ImageView iv_head;


    private UserBean userInfoBean;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        if (UserHelper.isLogin()) {
            userInfoBean = UserHelper.getUser();
            loadUserData();
        }

    }

    @Override
    protected void init() {
    }

    /**
     * 项目中维护个人信息 只用一个UserBean ,调用个人信息 后同步本地个人信息
     */
    private void loadUserData() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                Log.e("mango", "onOk: " + member);
                userInfoBean = new UserBean();
                userInfoBean.setMember_id(member.getMemberId());
                userInfoBean.setMember_name(member.getMemberName());
                userInfoBean.setMember_mobile(member.getMemberMobile());
                userInfoBean.setMember_avatar(member.getMemberAvatar());
                userInfoBean.setMember_level(member.getMemberLevel());
                userInfoBean.setIs_bank(member.getIsBank());
                userInfoBean.setIs_approve(member.getIsApprove());
                userInfoBean.setIs_paypwd(member.getIsPaypwd());
                userInfoBean.setTruename(member.getTruename());
                userInfoBean.setIdcard(member.getIdcard());
                userInfoBean.setAge(member.getEvolution().getAge());
                userInfoBean.setSex(member.getEvolution().getSex());
                userInfoBean.setChat_id(member.getChatId());
                userInfoBean.setChat_pwd(member.getChatPwd());
                userInfoBean.setPush_id(member.getPushId());
                userInfoBean.setEvolution_city(member.getEvolution().getEvolutionCity());
                userInfoBean.setEvolution_address(member.getEvolution().getEvolutionAddress());
                userInfoBean.setEvolution_city_id(member.getEvolution().getEvolutionCityId());


                if (ValidateUtils.isValidate(member.getMemberName())) {
                    tv_usename.setText(member.getMemberName());
                } else {
                    tv_usename.setText(member.getTruename());
                }
                tv_phone.setText(member.getMemberMobile());
                GlideHelper.INSTANCE.loadAvatar(iv_head, member.getMemberAvatar());
                UserHelper.syncCurrentUserInfo(userInfoBean);   //同步个人信息
            }

            @Override
            public void onError(int code, String errorMessage) {

            }
        });

//         加载客服数据
        NetworkManager.INSTANCE.post(Apis.get_kfu_info, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Index.get_kfu_info kefu_message = Index.get_kfu_info.parseFrom(response);
                ServiceBean serviceBean = new ServiceBean();
                serviceBean.setMember_id(kefu_message.getMemberId());
                serviceBean.setMember_name(kefu_message.getMemberName());
                serviceBean.setMember_mobile(kefu_message.getMemberMobile());
                serviceBean.setMember_avatar(kefu_message.getMemberAvatar());
                serviceBean.setChat_id(kefu_message.getChatId());
                serviceBean.setChat_pwd(kefu_message.getChatPwd());
                UserHelper.saveKeFuUserInfo(serviceBean);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @OnClick({R.id.mine_mil_zero, R.id.mine_mil_one, R.id.mine_mil_two,
            R.id.mine_mil_three, R.id.mine_mil_four,
            R.id.mine_mil_five, R.id.login_out, R.id.iv_head})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mine_mil_zero:
                startActivity(QrActivity.class);
                break;
            case R.id.mine_mil_one:
                startActivity(BankCardActivity.class);
                break;
            case R.id.mine_mil_two:
                WebViewActivity.startActivity(mContext, WebApis.policy);
                break;
            case R.id.mine_mil_three:
                startActivity(SettingActivity.class);
                break;
            case R.id.mine_mil_four:
                startChat();
                break;
            case R.id.mine_mil_five:
                startActivity(FeedBackActivity.class);
                break;
            case R.id.iv_head:
                PermissionHelper.getInstance().getPermission((FragmentActivity) mContext, new PermissionHelper.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        ImageHelper.showAvatarChoose(getActivity());
                    }

                    @Override
                    public void onFail() {
                        showToast("请先允许权限再使用此功能");
                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
        }
    }


    private void startChat() {
        boolean login = ChatHelper.getInstance().isLogin();
        if (login) {
            // 打开客服聊天
            ServiceBean keFuInfo = UserHelper.getKeFuInfo();
            ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
        } else {
            showToast("聊天登录中");
            MainApplication.getChatHelper().login(UserHelper.getUser().getChat_id(), UserHelper.getUser().getChat_pwd(), new LoginCallBack() {
                @Override
                public void onSuccess() {
                    //判断是否为客服
                    // 打开客服聊天
                    ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                    mContext.runOnUiThread(() -> showToast("人工客服回复时间：工作日9:00-12:00；13:30-18:00"));
                    ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
                }

                @Override
                public void onError(int code, String message) {
                    mContext.runOnUiThread(() -> showToast("聊天暂时登录失败"));
                }
            });
        }
    }

    public void reloadHead(String respone) {
       GlideHelper.INSTANCE.loadAvatar(iv_head,respone);
    }


}
